/**
 * 注释：生成验证码的函数因为GitHub上的不好用，所以我参考了这篇博客的实现方式的代码
 *      并且为了适用我的项目做了修改
 *      这个函数的著作权归原作者和我所有
 * 原作者：浅浅Chen
 * 博客地址：https://blog.csdn.net/chenjingshen1214/article/details/82627845
 */

const nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
    'L', 'M', 'N', 'O', 'P', 'Q', 'R',
    'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
    'y', 'z'
];

// 绘制验证码
function drawCode() {
    const canvas = document.getElementById("captcha_canvas"); //获取HTML端画布
    const context = canvas.getContext("2d"); //获取画布2D上下文
    context.fillStyle = "white"; //画布填充色
    context.fillRect(0, 0, canvas.width, canvas.height);

    // 创建渐变
    const gradient = context.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop("0", "magenta");
    gradient.addColorStop("0.5", "blue");
    gradient.addColorStop("1.0", "red");

    //清空画布
    context.fillStyle = gradient; //设置字体颜色
    context.font = "100px Arial"; //设置字体
    let rand = [];
    let x = [];
    let y = [];
    for (let i = 0; i < 4; i++) {
        rand[i] = nums[Math.floor(Math.random() * nums.length)];
        x[i] = i * 50 + 10;
        y[i] = Math.random() * 150 + 20;
        context.fillText(rand[i], x[i], y[i]);
    }

    //画3条随机线
    for (let i = 0; i < 3; i++) {
        drawLine(canvas, context);
    }

    // 画30个随机点
    for (let i = 0; i < 30; i++) {
        drawDot(canvas, context);
    }
    convertCanvasToImage(canvas);

    //返回验证码token
    return rand;
}

// 随机线
function drawLine(canvas, context) {
    context.moveTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //随机线的起点x坐标是画布x坐标0位置，y坐标是画布高度的随机数
    context.lineTo(Math.floor(Math.random() * canvas.width), Math.floor(Math.random() * canvas.height)); //随机线的终点x坐标是画布宽度，y坐标是画布高度的随机数
    context.lineWidth = 0.9; //随机线宽
    context.strokeStyle = 'rgba(50,50,50,0.3)'; //随机线描边属性
    context.stroke(); //描边，即起点描到终点
}
// 随机点(所谓画点其实就是画1px像素的线，方法不再赘述)
function drawDot(canvas, context) {
    let px = Math.floor(Math.random() * canvas.width);
    let py = Math.floor(Math.random() * canvas.height);
    context.moveTo(px, py);
    context.lineTo(px + 5, py + 5);
    context.lineWidth = 0.7;
    context.stroke();

}
// 绘制图片
function convertCanvasToImage(canvas) {
    let image = document.getElementById("captcha_img");
    image.src = canvas.toDataURL("image/png");
    return image;
}

export {drawCode}